<?php
/**
 * 前台操作及数据调用接口
 * 
 * 发表评论：
 * 		1.普通方式直接把表单提交到 op.php?ac=postcomment 剩下的工作由系统负责
 * 		2.AJAX方式提交到：op.php?ac=postcomment&inajax=1 ，返回JSON数据，需在主题js中对返回结果进行处理。
 * 		评论失败：status:error，msg:错误消息
 * 		评论成功：status:success，msg:提示信息，data:评论信息
 * 
 * 获取一条评论：
 * 		GET：op.php?ac=getcomment&id=评论ID
 * 		返回：评论数据(JSON格式)
 * 
 * 获取评论列表：
 * 		GET: op.php?ac=getcommentlist&postid=文章ID&page=页数&pagesize=每页显示数量
 * 		返回：多条评论组成的JSON数据
 * 
 * 删除一条评论：
 * 		GET: op.php?ac=delcomment&id=评论ID
 * 		返回：成功： status:success，失败：stauts:error
 */

require 'include/common.php';

//评论消息提示
function comment_msg($msg, $status='error') {
	global $_USER,$comment_id;
	if ( $_GET['inajax'] ) {
		$output = array('status'=>$status);
		if ( is_string($msg) ) {
			$output['msg'] = $msg;
		} elseif ( is_array($msg) ) {
			$output['msg'] = '';
			$output['data'] = $msg;
		}
		ajax_out($output);
	} else {
		$refer = $_USER['refer'];
		$refer .= '#comment-'.$comment_id;
		if ( $status == 'error' ) {
			show_msg($msg);
		} else {
			if ( is_array($msg) ) {
				redirect($refer);
			} else {
				show_msg($msg, $refer);
			}
		}
	}
}

//发表评论
if ( $_GET['ac'] == 'postcomment' ) {
	
	if ( !check_perm('comment','post') ) {
		comment_msg(__('对不起，您没有发表评论的权限。'));
	}
	$lasttime = (int)get_cookie('last_comment_time');
	$timelimit = (int)$_USER['permission']['comment']['timelimit'];
	if ( $timelimit && NOW - $lasttime < $timelimit ) {
		comment_msg(__('你的评论速度太快了，%d 秒后再发吧。', $timelimit - (NOW-$lasttime)));
	}
	$comment = array(
		'postid'   => intval($_POST['comment_postid']),
		'author'   => check_str($_POST['comment_author']),
		'email'    => strtolower($_POST['comment_email']),
		'url'      => check_str($_POST['comment_url']),	
		'content'  => trim($_POST['comment_content']),
		'dateline' => NOW,
		'ip'       => $_USER['ip'],
		'agent'    => $_SERVER['HTTP_USER_AGENT'],
		'status'   => 0
	);
	if ( !empty($comment['url']) && !preg_match('/^http/i', $comment['url']) ) {
		$comment['url'] = 'http://'.$comment['url'];
	}
	$post = $db->fetch_one_array("SELECT id,alias,`status`, commentstatus,`type` FROM ".tname('post')." WHERE id = '$comment[postid]'");
	if ( !$post || $post['status'] != 1 ) {
		comment_msg(__('文章不存在'));
	} elseif ( $post['commentstatus'] == 0 ) {
		comment_msg(__('这篇文章不允许评论。'));
	}
	
	if ( $_USER['id'] ) {
		$comment['userid'] = $_USER['id'];
		$comment['author'] = $_USER['name'];
		$comment['email']  = $_USER['email'];
		$comment['url']    = $_USER['url'];
	} else {
		if ( empty($comment['author']) ) {
			comment_msg(__('请填写您的名称。'));
		} elseif ( $db->result("SELECT id FROM ".tname('user')." WHERE username = '$comment[author]'") ) {
			comment_msg(__('您输入的昵称是本站会员，但是你还没有登录，如果你是该用户，请先登录后再发表评论。'));
		} elseif ( empty($comment['email']) ) {
			comment_msg(__('请填写您的邮箱，我们不会公开。'));
		} elseif ( !is_email($comment['email']) ) {
			comment_msg(__('%s 不是有效的Email地址。', $comment['email']));
		} elseif ( $db->result("SELECT id FROM ".tname('user')." WHERE email = '$comment[email]'") ) {
			comment_msg(__('您输入的邮箱地址是本站会员所有，如果你是该用户，请先登录后再发表评论。'));
		}
	}
	//验证码
	if ( check_perm('comment','seccode') ) {
		if ( empty($_POST['comment_seccode']) ) {
			comment_msg(__('请输入验证码。'));
		}
		session_start();
		if ( strtolower($_POST['comment_seccode']) != strtolower($_SESSION['seccode']) ) {
			comment_msg(__('您输入的验证码有误。'));
		}	
	}
	if ( empty($comment['content']) ) {
		comment_msg(__('请输入评论内容。'));
	} elseif ( $_USER['permission']['comment']['maxchar'] && strlen($comment['content']) > $_USER['permission']['comment']['maxchar'] ) {
		comment_msg(__('评论内容长度不能大于 %d 字节', $_USER['permission']['comment']['maxchar']));
	}
	if ( ! check_perm('comment','needcheck') ) {
		$comment['status'] = 1;
	}
	
	$comment['content'] = preg_replace(array("/(\r\n){3,}/","/(\r){3,}/","/(\n){3,}/"),array("\${1}","\${1}","\${1}"),$comment['content']);
	$comment['content'] = nl2br(check_str($comment['content']));
	
	if ( preg_match_all('/\[re=(\d+),([^\]]+?)]/is',$comment['content'], $matches) ) {
		$matches = $matches[1];
		$matches = array_unique($matches);
		if ( $matches ) {
			$atuids = '';
			$query = $db->query("SELECT userid FROM ".tname('comment')." WHERE id IN (".simplode($matches).")");
			while ( $row = $db->fetch_array($query) ) {
				if ( $row['userid'] ) {
					$atuids .= ",$row[userid]";
				}
			}
			if ( !empty($atuids) ) {
				$comment['atuids'] = $atuids.',';
			}
		}
	} 
	
	$comment_id = $db->insert('comment', $comment);
	
	if ( $_USER['id'] ) {
		$db->query("UPDATE ".tname('user')." SET comments = comments + 1 WHERE id = '$_USER[id]'");
	}
	set_cookie('last_comment_time', NOW, 86400);
	
	do_action('post_comment', $comment);
	
	if ( check_perm('comment','needcheck') ) {
		comment_msg(__('您的评论已成功发布，但是需要管理员审核后才能显示。'), 'success');
	} else {
		$db->query("UPDATE ".tname('post')." SET comments = comments + 1 WHERE id = '$comment[postid]'");
		comment_msg($comment, 'success');
	}
	
//删除一条评论
} elseif ( $_GET['ac'] == 'delcomment' ) {
	
	$id = intval($_GET['id']);
	if ( ! is_admin() || ! check_perm('comment','del') ) {
		ajax_out(array('status'=>'error'));
	} 
	if ( delete_comment($id) ) {
		ajax_out(array('status'=>'success'));
	} else {
		ajax_out(array('status'=>'error'));
	}
	
//获取一条评论数据，返回JSON数据
} elseif ( $_GET['ac'] == 'getcomment' ) {
	if ( $_GET['id'] && is_numeric($_GET['id']) ) {
		require_once JBLOG_INC.'func_comment.php';
		$comment = array();
		if ( get_comment(intval($_GET['id'])) ) {
			$comment = array(
				'id'          => comment('id', true),
				'postid'      => comment('postid', true),
				'userid'      => comment('userid', true),
				'author'      => comment('author', true),
				'author_link' => comment('author_link', true),
				'avatar'      => comment('avatar', true),
				'url'         => comment('url', true),
				'content'     => comment('content', true),
				'dateline'    => comment('dateline', true),
				'posttime'    => comment('posttime', true),
			);			
		}
		ajax_out($comment);
	}
	
//获取评论列表
} elseif ( $_GET['ac'] == 'getcommentlist' ) {
	
	initGP(array('postid','page','pagesize'),'G','int');
	
	require_once JBLOG_INC.'func_comment.php';
	
	$page = max(1, $page);
	!$pagesize && $pagesize = config('pagesize');
	query_comment($postid, $pagesize, ($page-1)*$pagesize);
	$data = array();
	if ( have_comment() ) {
		while ( fetch_comment() ) {
			$row = array(
				'id'          => comment('id',true),
				'postid'      => comment('postid',true),
				'userid'      => comment('userid',true),
				'author'      => comment('author',true),
				'author_link' => comment('author_link',true),
				'avatar'      => comment('avatar',true),
				'url'         => comment('url',true),
				'content'     => comment('content',true),
				'dateline'    => comment('dateline',true),
				'posttime'    => comment('posttime',true),
			);
			$data[] = $row;
		}
	}
	ajax_out($data);
	
//加密日志内容获取
} elseif ( $_GET['ac'] == 'getprotectedpost' ) {
	
	initGP(array('id','password','field'),'P');
	
	$field != 'excerpt' && $field = 'content';
	if ( is_numeric($id) && !empty($password) ) {
		$post = $db->fetch_one_array("SELECT id,`status`,password,{$field} FROM ".tname('post')." WHERE id = '$id'");
		if ( !$post || $post['status'] != 1 ) {
			ajax_out(array('status'=>'error','data'=>__('文章不存在。')));
		} elseif ( $post['password'] != $password ) {
			ajax_out(array('status'=>'error','data'=>__('密码错误。')));
		} else {
			set_cookie("protected_post_{$id}", $password);
			ajax_out(array('status'=>'success','data'=>apply_filter("post_{$field}", $post[$field])));
		}
	}
	
}
?>